package xyz.naokeziteng.data_structure.rbtree;

/**
 * @author hawk
 * @date 2022/9/27
 * @desc
 **/
public class RBTree<K extends Comparable<K>, V> {
    //红色
    private static final boolean RED = true;
    //黑色
    private static final boolean BLACK = true;

    private Node root;
    private int size;

    public int getSize() {
        return this.size;
    }

    public boolean isEmpty() {
        return this.size == 0;
    }

    private boolean isRed(Node node) {
        if (node == null) {
            return false;
        }
        return node.color;
    }

    //向二分搜索树中添加新的元素
    public void add(K key, V value) {
        root = add(root, key, value);
        root.color = BLACK;
    }

    //向以Node为根的二分搜索树中添加元素e,递归算法
    //返回插入新节点后的根
    private Node add(Node node, K key, V value) {
        if (node == null) {
            size++;
            return new Node(key, value);
        }

        if (node.key.compareTo(key) < 0) {
            node.right = add(node.right, key, value);
        } else if (node.key.compareTo(key) > 0) {
            node.left = add(node.left, key, value);
        }

        if (!isRed(node.left) && isRed(node.right)) {
            node = leftRotate(node);
        }
        if (isRed(node.left) && isRed(node.left.left)) {
            node = rightRotate(node);
        }
        if (isRed(node.left) && isRed(node.right)) {
            flipColor(node);
        }

        return node;
    }

    //树节点
    private class Node {
        private K key;
        private V value;
        //左子树
        private Node left;
        //右子树
        private Node right;
        //颜色
        private boolean color;

        public Node(K key, V value) {
            this.key = key;
            this.value = value;
            left = right = null;
            this.color = RED;
        }
    }

    //左旋转
    //       y                             x
    //      / \                          /   \
    //     T1  x     向右旋转（y）        y     T3
    //        / \   - - - - - - - ->   / \
    //      T2  T3                    T1 T2
    private Node leftRotate(Node y) {
        Node x = y.right;
        Node t2 = x.left;
        y.right = t2;
        x.left = y;
        x.color = y.color;
        y.color = RED;
        return x;
    }

    //右旋转
    //       y                             x
    //      / \                          /   \
    //     x  T4     向右旋转（y）        z     y
    //    / \      - - - - - - - ->   / \   / \
    //   z  T3                       T1 T2 T3 T4
    //  / \
    // T1  T2
    private Node rightRotate(Node y) {
        Node x = y.left;
        Node t3 = x.right;
        y.left = t3;
        x.right = y;
        x.color = y.color;
        y.color = RED;
        return x;
    }

    //颜色翻转
    private void flipColor(Node y) {
        Node left = y.left;
        Node right = y.right;
        left.color = right.color = BLACK;
        y.color = RED;
    }
}
